package com.fwj.config;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;

import com.fwj.exception.EsbSynException;
import com.fwj.pojo.ServiceInfo;
import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class F5ServicesConfig {
    private static List<ServiceInfo> _instance;
    private void init() throws EsbSynException {
        Gson gson = new Gson();
        try {
            String    jsonStr = getJson();
            // 读取json文件,反射到serviceinfo类中.
            _instance = gson.fromJson(jsonStr,
                    new TypeToken<List<ServiceInfo>>() {}.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            throw new EsbSynException("Json解析失败!");
        }
    }

    private String getJson() throws EsbSynException {
        StringBuffer buffer = new StringBuffer();
        //获取输入流
        InputStream is =
                Thread.currentThread().getContextClassLoader().getResourceAsStream("f5-bigip.json");
        BufferedReader in = new BufferedReader(new
                InputStreamReader(is, Charset.forName("UTF-8")));
        String line = "";
        try {
            while ((line = in.readLine()) != null){
                buffer.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
            throw new EsbSynException("读取json服务器配置文件失败");
        }finally{
            try {
                in.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return buffer.toString();
    }

    public static List<ServiceInfo> getInstance() throws EsbSynException {
        F5ServicesConfig config = new F5ServicesConfig();
        config.init();
        return _instance;
    }
}